#pragma once
#include <vector>
#include <string>
#include <fstream>
#include <map>
#include "md5.h"
#define BUFFER_SIZE 1024
#define COPYDATA_MD5_UPDATE	3
using namespace std;
class CWorker
{
	vector<TCHAR*>* pFiles;
	map<string, TCHAR*> m_map;
	
public:
	HWND hwnd;
	CWorker(void);
	~CWorker(void);

	void assign(vector<TCHAR*>* _pFiles)
	{
		pFiles = _pFiles;
	}

	void start()
	{		
		char *chBuffer = new char[BUFFER_SIZE];
		DWORD dwBytesRead    = 0;
		char hex_output[16*2 + 1];
		string s_hex_output;		

		wofstream ofsrm;
		ofsrm.open("c:\\duplicate.txt");


		for( vector<TCHAR*>::iterator itr = pFiles->begin();
			itr != pFiles->end();
			itr++)
		{


			HANDLE hFile  = INVALID_HANDLE_VALUE;

			hFile = CreateFile(*itr,               // file to open
							   GENERIC_READ,          // open for reading
							   FILE_SHARE_READ,       // share for reading
							   NULL,                  // default security
							   OPEN_EXISTING,         // existing file only
							   FILE_ATTRIBUTE_NORMAL, // normal file
							   NULL);   

			DWORD dw = GetLastError(); 
			if (hFile == INVALID_HANDLE_VALUE) 
			{
				continue;
			}

			md5_state_t state;
			md5_byte_t digest[16];
			md5_init(&state);

			do
			{
				if (ReadFile(hFile, chBuffer, BUFFER_SIZE, &dwBytesRead, NULL)) 
				{
					chBuffer[dwBytesRead]='\0';
					md5_append(&state, (const md5_byte_t *)chBuffer, strlen(chBuffer));
				}

			} while (dwBytesRead == BUFFER_SIZE); 

			//ATLTRACE( atlTraceUI, 0, _T("%s\n"), *itr);
			
			md5_finish(&state, digest);

			for (int di = 0; di < 16; ++di)
				sprintf(hex_output + di * 2, "%02x", digest[di]);			

			hex_output[32] = '\0';

			s_hex_output = hex_output;
			map<string, TCHAR*>::iterator map_itr = m_map.end();


			COPYDATASTRUCT cpd;

			CString strDataToSend(hex_output);

			cpd.dwData = COPYDATA_MD5_UPDATE;
			cpd.cbData = 33;
			cpd.lpData = (void*)hex_output;

			SendMessage(hwnd, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)&cpd);


			if( map_itr == m_map.find(s_hex_output) )
			{
				// not found
				m_map[s_hex_output] = *itr;
			}
			else
			{
				DWORD dwBytesWritten = 0;


				//_stprintf(DataBuffer, _T("%s\n%s\n%s\n"), *itr, m_map[s_hex_output], s_hex_output.c_str());

				ofsrm<<*itr<<"\n"<<m_map[s_hex_output]<<"\n"<<s_hex_output.c_str()<<"\n\n";



				ATLTRACE( atlTraceUI, 0, _T("%s\n"), *itr);
				ATLTRACE( atlTraceUI, 0, _T("%s\n"), m_map[s_hex_output]);
				ATLTRACE( atlTraceUI, 0, _T("%S\n"), hex_output);
				ATLTRACE( atlTraceUI, 0, _T("\n"));
			}
			CloseHandle(hFile);

			//printf("%s", hex_output);
			//ATLTRACE( atlTraceUI, 0, _T("%S\n"), hex_output);

		}

		ofsrm.close();
	}
};

